import { PageEnum } from "@/enums/pageEnum";
import { useAuthStore } from "@/stores/auth";
import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";

const routes: RouteRecordRaw[] = [
  {
    path: "/login",
    name: "Login",
    component: () => import("@/views/Login/index.vue"),
    meta: {
      title: "登录",
      guestOnly: true, // 仅未登录可访问
      hidden: true,
    },
  },
  {
    path: "/users",
    name: "UserManagement",
    component: () => import("@/views/User/index.vue"),
    meta: {
      title: "用户管理",
      icon: "user-outlined",
      requiresAuth: true,
    },
  },
  {
    path: "/enterprise",
    name: "Enterprise",
    component: () => import("@/views/Enterprise/index.vue"),
    meta: {
      title: "企业管理",
      icon: "qrcode-outlined",
      requiresAuth: true,
    },
  },
  {
    path: "/account",
    name: "Account",
    component: () => import("@/views/Account/index.vue"),
    meta: {
      title: "账号管理",
      icon: "idcard-outlined",
      requiresAuth: true,
    },
  },
  {
    path: "/tags",
    name: "Tags",
    component: () => import("@/views/Tags/index.vue"),
    meta: {
      title: "标签管理",
      icon: "tags-outlined",
      requiresAuth: true,
    },
  },
  {
    path: "/school",
    name: "School",
    component: () => import("@/views/School/index.vue"),
    meta: {
      title: "院校管理",
      icon: "home-outlined",
      requiresAuth: true,
    },
  },
  {
    path: "/model",
    name: "Model",
    component: () => import("@/views/Model/index.vue"),
    meta: {
      title: "模型管理",
      icon: "setting-outlined",
      requiresAuth: true,
    },
  },

  {
    path: "/system",
    name: "System",
    meta: {
      title: "系统设置",
      icon: "setting-outlined",
      requiresAuth: true,
    },
    children: [
      {
        path: "model",
        name: "Model",
        component: () => import("@/views/Model/index.vue"),
        meta: {
          title: "模型管理",
          requiresAuth: true,
        },
      },
      {
        path: "template",
        name: "Template",
        component: () => import("@/views/Template/index.vue"),
        meta: {
          title: "模板管理",
          requiresAuth: true,
        },
      },
    ],
  },
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
});

// 路由守卫示例
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore();

  // 验证登录状态
  if (to.meta.requiresAuth && !authStore.isAuthenticated) {
    return next({ name: "Login", query: { redirect: to.fullPath } });
  }

  // 已登录用户禁止访问登录页
  if (to.meta.guestOnly && authStore.isAuthenticated) {
    // return next(import.meta.env.BASE_URL)
    return next(PageEnum.ACCOUNT_USER);
  }
  next();
});

export default router;
